package com.ruoyi.web.controller.web;

import com.ruoyi.common.annotation.UserLoginToken;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.ResultCodeEnum;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.shiro.service.SysPasswordService;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.core.Cookie.CookieUtils;
import com.ruoyi.web.core.jwt.JwtUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author tang ao long
 * @Date 2020-08-26 16:30
 * @Version 1.0
 */
@RestController
@RequestMapping("/web/user")
public class UserController extends BaseController {

    @Autowired
    ISysUserService userService;

    @Autowired
    SysPasswordService passwordService;

    //登录
    @PostMapping("/login")
    public Object login(HttpServletRequest httpServletRequest,HttpServletResponse httpServletResponse,@RequestParam String loginName,@RequestParam String password){
        JSONObject jsonObject=new JSONObject();
        SysUser userForBase=userService.selectUserByLoginNameAndType(loginName,"01");
        if(userForBase==null){
            jsonObject.put("message","登录失败,用户不存在");
            return jsonObject;
        }else {
            if (!passwordService.matches(userForBase, password)){
                jsonObject.put("message","登录失败,密码错误");
                return jsonObject;
            }else {
                //设置 jwt token 30分钟后过期
                String token = JwtUtil.sign(userForBase.getUserId());
                //CookieUtils.setCookie(httpServletRequest,httpServletResponse,"token", token);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }
    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage(){
        return "你已通过验证";
    }

}
